import { WorkflowNodeItem } from './../domain/models/workflowNodeItem';
import { IQueryObject } from 'tiny-entity2/queryObject';
import { FlowNode } from "../domain/models/flowNode";
import { Transaction } from "tiny-entity2";
import { ApiDataContext } from "../domain/apiDataContext";
import { BaseService } from "./baseService";

export class FlowNodeService extends BaseService {
    CreateFlowNode(entity: FlowNode, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            // let has = await ctx.FlowNode.First(x => x.name == $args1, { $args1: entity.name });
            // if (has) {
            //     throw new ServiceException(`【${entity.name}】的节点已经存在！`);
            // }

            let d = new FlowNode();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    UpdateFlowNode(entity: FlowNode, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            // let has = await ctx.FlowNode.First(x => x.name == $args1 && x.id != $args2, { $args1: entity.name, $args2: entity.id });
            // if (has) {
            //     throw new ServiceException(`【${entity.name}】的节点已经存在！`);
            // }

            let d = new FlowNode();
            d.ConverToEntity(entity);
            return ctx.Update(d);
        });
    }
    GetFlowNodeById(id: string) {
        let ctx = new ApiDataContext();
        return ctx.FlowNode.First(x => x.id == $args1, { $args1: id });
    }
    QueryFlowNode(params: FlowNodeQueryParams) {
        let ctx = new ApiDataContext();
        let q = ctx.FlowNode as IQueryObject<FlowNode>;

        if (params.workflowId) {
            q = q.Where(x => x.workflowId == $args1, { $args1: params.workflowId });
        }
        return q.ToList();
    }

    DeleteFlowNode(id: string, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async () => {
            await ctx.Delete<FlowNode>(x => x.id == $args1, ctx.FlowNode, { $args1: id });
            await ctx.Delete<WorkflowNodeItem>(x => x.flowNodeId == $args1, ctx.WorkflowNodeItem, { $args1: id });
        })
    }
}

export interface FlowNodeQueryParams {
    workflowId?: string;
    needInfo?: boolean;
}